#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

import logging
import time
import datetime
import os
import oauth
import sys
import simplejson
import random
import urllib
from init import *
class MixiUserDB(db.Model):
    UserId = db.StringProperty()
    UserName = db.StringProperty()
    Profile = db.TextProperty()
    ProfileImage = db.TextProperty()
    RKTouchToken = db.StringProperty()
    
class ShiritoriDataDB(db.Model):
    day=db.StringProperty()
    create_day=db.DateTimeProperty()
    data=db.TextProperty()
    displayName=db.StringProperty()
    UserID=db.StringProperty()
    ThumbnailUrl=db.TextProperty()
    lat=db.StringProperty()
    lng=db.StringProperty()
    SpotID=db.StringProperty()

class TodayWordDB(db.Model):
    day=db.StringProperty()
    create_day=db.DateTimeProperty()
    word=db.TextProperty()

class ShiritoriMain(webapp.RequestHandler):
    def __init__(self):
        self.keys=consumer_keys("./lib/data/key.json")
        self.mixi={
            "scope":'r_profile r_voice w_voice',
            "AuthUrl":'https://mixi.jp/connect_authorize.pl?client_id=%s&response_type=code&display=pc&scope=%s',
            "api":{
                   'voice':{
                            'get':'http://api.mixi-platform.com/2/voice/statuses/@me/user_timeline?oauth_token=%s',
                            'post':'http://api.mixi-platform.com/2/voice/statuses/update?oauth_token=%s&status=%s'
                            },
                   'profile':'http://api.mixi-platform.com/2/people/@me/@self?oauth_token=%s'
                }
        }
        """ ロケタッチ """
        self.touch={
            # client_id & redirect URI
            "AuthUrl":'https://tou.ch/oauth2/authenticate?client_id=%s&response_type=code&redirect_uri=%s',
            "api":{
                   "home_timeline":"https://api.loctouch.com/v1/home_timeline?oauth_token=%s",
                   "search_user":"https://api.loctouch.com/v1/users/search?oauth_token=%s&query=%s",
                   "search_spot":"https://api.loctouch.com/v1/spots/search?oauth_token=%s&lat=%s&lng=%s",
                   "post_touch":"https://api.loctouch.com/v1/touches/touch?oauth_token=%s&spot_id=%s&text=%s"
            }
        }
    # POST対応
    def post(self):
        cookies = self.request.cookies
        self.token = cookies.get('mixi_access_token',"")
        self.rk_token = cookies.get('rktch_access_token',"")
        self.refresh_token = cookies.get('mixi_refresh_token',"")
        self.formType=self.request.get("create")
        
        commit=self.request.get("commits", default_value=0)
        #commit_touch=self.request.get("commit_touch", default_value=0)
        commit_touch="1"
        mentions = urllib.quote(u"%s from http://%s/".encode("UTF-8") % ("今、「とりとロック」(しりとりアプリ)で遊んでるよ！", os.environ["HTTP_HOST"]))
        if self.formType == "1":
            #ur = self.mixi["api"]["voice"]["post"] % (self.token, self.request.get("texts"))
            dates=GetGMT(hour=9)
            sdb=ShiritoriDataDB(day=dates.strftime("{'year':%Y,'month':%m,'day':%d}"),
                                create_day=dates,
                                data=self.request.get("texts"),
                                displayName=self.request.get("displayName"),
                                UserID=self.request.get("userID"),
                                ThumbnailUrl=self.request.get("thumbnailUrl"),
                                lat=self.request.get("latitude"),
                                lng=self.request.get("longitude"),
                                SpotID=self.request.get("spotID")
                                )
            sdb.put()
            """
                mixi voiceへ
            """
            ur = self.mixi["api"]["voice"]["post"] % (self.token, mentions)
            t = 0
            #self.response.out.write(commit)
            if commit == "1":
                t = urlfetch.fetch(url=ur, method=urlfetch.POST)
                #self.response.out.write(t.status_code)
            """
                ロケタッチへ
            """
            url = self.touch["api"]["post_touch"] % (self.rk_token, self.request.get("spotID"), mentions)
            # self.response.out.write(url)
            if self.request.get("spotID") != "" and self.rk_token != "" and commit_touch == "1":
                rkt = urlfetch.fetch(url=url, method=urlfetch.POST)
                if rkt.status_code == 200:
                    # self.response.out.write(rkt.content)
                    self.redirect('/')
            """
                / ロケタッチへ
            """
        #if t is not 0 and t.status_code == 200:
        self.redirect('/')
    # GET対応   
    def get(self):
        cookies = self.request.cookies
        self.token = cookies.get('mixi_access_token', "")
        self.refresh_token = cookies.get('mixi_refresh_token', "")
        OAUTH2_URL =  self.mixi["AuthUrl"] % (self.keys["mixi"][os.environ["SERVER_NAME"]]["consumer_key"],self.mixi["scope"])
        token = cookies.get('mixi_access_token',"")
        refresh_token = cookies.get('mixi_refresh_token',"")
        token_flag = 0
        pofileApi = self.mixi["api"]["profile"] % self.token
        VoiceApi = self.mixi["api"]["voice"]["get"] % self.token
        json={}
        jsons = ""
        tv = {}
        """
            Today Words
        """
        dates=GetGMT(hour=9)
        day=dates.strftime("{'year':%Y,'month':%m,'day':%d}")
        dbs = TodayWordDB.all()
        dbs.filter("day =",day)
        res = dbs.fetch(1)
        #for i in res:
        word = simplejson.loads(res[0].word)
        tv["todays_word"]=word["reading"]
        if token != "" :
            token_flag = 1
            f=""
            v=""
            f = urlfetch.fetch(pofileApi)
            # self.response.out.write(f.status_code)
            if(f.status_code==401):
                self.redirect('/refresh')
            if(f.status_code==200):
                token_flag = 1
                jsons = f.content;
                json=simplejson.loads(f.content)
                v = urlfetch.fetch(VoiceApi)
                jsonv={}
                if(v.status_code==200):
                    jsonv=simplejson.loads(v.content)
                tv["profile"] = json
                tv["voice"] = jsonv
                tv["consumer_key"] = self.keys["mixi"][os.environ["SERVER_NAME"]]["consumer_key"]
                tv["consumer_secret_key"] = self.keys["mixi"][os.environ["SERVER_NAME"]]["consumer_secret_key"]
                #しりとりデータ
                sdb = ShiritoriDataDB.all()
                sdb.order("-create_day")
                results=sdb.fetch(5)
                if len(results) is 0:
                    tv["todays_word_last"]=word["last"]
                if len(results) > 0:
                    t=dates.strftime("{'year':%Y,'month':%m,'day':%d}")
                    if results[0].day != t:
                        tv["todays_word_last"]=word["last"]
                    else:
                        tv["current_word"]=results[0].data
                        tv["todays_word_last"]=results[0].data[len(results[0].data)-1]
                    tv["histry"]=results
            else :
                token_flag = 0
                        
        tv["oauthUrl"]=OAUTH2_URL
        tv["login"]=token_flag
        """
            ロケタッチ
        """
        tv["touchAuthUrl"]=""#ロケタッチAuth URL
        rktch_uri = 'http://%s/rktch' % os.environ["HTTP_HOST"]#SERVER_NAME
        tv["rklogin"]=0
        if( cookies.get("rktch_access_token", "") == "" ):
            tv["touchAuthUrl"]=self.touch["AuthUrl"] % (self.keys["rktouch"][os.environ["SERVER_NAME"]]["client_id"], rktch_uri)
        if( cookies.get("rktch_access_token", "") ):
            tv["rklogin"]=1
            t = cookies.get("rktch_access_token", "")
            #h = self.touch["api"]["home_timeline"] % (t)
            #lat:35.6851543,lng:139.7214186
            #35.7141797,139.7531217
            loc={"lat":35.7141797,"lng":139.7531217}
            if self.request.get("lat") is not "" and self.request.get("lat"):
                loc={"lat":self.request.get("lat"),"lng":self.request.get("lng")}
            h = self.touch["api"]["search_spot"] % ( t, loc["lat"], loc["lng"] )
            rkapi = urlfetch.fetch(h)
            tv["rktouch"]={"spot":{}}
            if rkapi.status_code == 200:
                tv["rktouch"]["spot"]=simplejson.loads(rkapi.content)
                #self.response.out.write(rkapi.status_code)
        """
            /ロケタッチ
        """
        tmpl_path = os.path.dirname(__file__)+"/tmpl/"
        path = os.path.join(tmpl_path, 'index.tmp')
        self.response.out.write(template.render(path, tv))

class Test(webapp.RequestHandler):
    def get(self):
        pass
      
application = webapp.WSGIApplication([('/', ShiritoriMain)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
